package com.smcdd.cdb.dbo.cdb_dbo.service.presenter;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;

import com.smcdd.cdb.dbo.cdb_dbo.R;
import com.smcdd.cdb.dbo.cdb_dbo.app.App;
import com.smcdd.cdb.dbo.cdb_dbo.network.HttpObserver;
import com.smcdd.cdb.dbo.cdb_dbo.network.factory.RetrofitFactory;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.AllUser;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.BaseResponseEntity;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.Function;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.Hardware_report;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.ParseCode;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.Picture;
import com.smcdd.cdb.dbo.cdb_dbo.service.entity.UpdateVersion;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.DataManager;
import com.smcdd.cdb.dbo.cdb_dbo.service.maneger.NetWorkCodeInfo;
import com.smcdd.cdb.dbo.cdb_dbo.service.view.IMainAc;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.CodeActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.DateInfosActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.FirmwareActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.GetHardwareActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.GroupingActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.HardwareActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.LamplightActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.MainActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.MenDianActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.NetInActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.PaperBHActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.PassWordActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.UpdateCdbActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.WebActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.activity.WifiActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.adapter.FunctionRecyclerAdapter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.adapter.MianRecyclerAdapter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BaseActivity;
import com.smcdd.cdb.dbo.cdb_dbo.ui.base.BasePresenter;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.DialogUtils;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.IsVersion;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainEncry;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ObtainVersion;
import com.smcdd.cdb.dbo.cdb_dbo.ui.utils.ToastUtil;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.SelectPicPopupWindow;
import com.smcdd.cdb.dbo.cdb_dbo.ui.widget.SimpleDialog;
import com.smcdd.cdb.dbo.cdb_dbo.zhhzxing.activity.CaptureActivity;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * 作者：Administrator on 2017/6/19 10:37
 * 邮箱：zhanghuaiha@gmail.com
 */

public class MainPresenter extends BasePresenter<IMainAc> {
    private List<Picture> mList;
    private MianRecyclerAdapter mianRecyclerAdapter;
    private MainActivity mainActivity;
    private static final int PHOTO_CODE = 234;
    private static final int CUT_USER = 4;
    private static final int REQUEST_CODE = 5;
    private static final int SAO_CODE = 6;
    private static final int WITHDRAW = 7;
    private static final int HARDWARE_FAULT = 8;
    private static final int GREEN_LIGHTING = 9;
    private static final int UPDATE_CDB = 10;
    private static final int GET_FIRMWARE = 11;
    private static final int SEND_FACTORY = 12;
    private static final int PAPER_BH = 13;
    private SelectPicPopupWindow menuWindow;
    private static final int PHOTO_REQUEST_CAREMA = 1;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 3;// 从相册中选择
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private File tempFile;
    private DataManager manager;
    private CompositeSubscription mCompositeSubscription;
    private FunctionRecyclerAdapter adapter;
    private String versionCode;
    private String id;
    private String udid = "";
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SAO_CODE:
                getMessage(NetWorkCodeInfo.MESSAGE_STATUS, (String)msg.obj);
                    break;
                case WITHDRAW:
                    getMessage(NetWorkCodeInfo.MESSAGE_STATUS, (String)msg.obj);
                    break;
                default:
                    break;
            }
        }
    };
    private Dialog progressDialog;
    private Dialog selectDialog;
    private SimpleDialog simpleDialog;
    private SimpleDialog selfDialog;
    private Dialog dialog;
    private TextView main_cut_user;
    private Dialog codeDialog;
    private TextView canel;
    private TextView wifi;
    private TextView mami;
    private TextView dialog_photo;


    public MainPresenter(BaseActivity context) {
        super(context);
    }

    public void loadContacts(String udid){
        this.udid = udid;
        mainActivity = getView().getMainActivity();
        main_cut_user = getView().getMain_cut_user();
        manager = new DataManager(mContext);
        versionCode = ObtainVersion.getVersionName(mContext);
        id = App.SP.getString("id", "");
        mCompositeSubscription = new CompositeSubscription();
        dialog();
        CodeDialog();
        setAdapter();
       // loadData();
        loadNetWork(udid);
    }



    //9宫格数据获取
    private void loadNetWork(String udid) {
        String tiem = System.currentTimeMillis() + "";
        Map<String,String> map = new LinkedHashMap<>();
        map.put("rf","2");
        map.put("ts",tiem);
        map.put("v",versionCode);
        map.put("i",NetWorkCodeInfo.FUNCTIONS);
        map.put("udid",udid);
        map.put("eid",id);
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry",encry1);
        RetrofitFactory.getmInstanse().mApi.getFunction(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<List<Function>>>() {
                    @Override
                    public void success(BaseResponseEntity<List<Function>> listBaseResponseEntity) {
                        if (listBaseResponseEntity.code == 200) {
                            List<Function> data = listBaseResponseEntity.data;
                            adapter.addData(data);
                        }else {
                            ToastUtil.showToast(listBaseResponseEntity.message);
                        }
                        getVersion();
                        netWork();
                        progressDialog.dismiss();
                    }
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        progressDialog.dismiss();
                    }
                });


    }

    //获取最新版本
    public void getVersion(){
        String tiem = System.currentTimeMillis() + "";
        Map<String,String> map = new LinkedHashMap<>();
        map.put("rf","2");
        map.put("ts",tiem);
        map.put("v",versionCode);
        map.put("i",NetWorkCodeInfo.VERSION);
        map.put("udid",udid);
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry",encry1);
        RetrofitFactory.getmInstanse().mApi.getVersion(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<UpdateVersion>>() {
                    @Override
                    public void success(BaseResponseEntity<UpdateVersion> updateVersionBaseResponseEntity) {
                        if (updateVersionBaseResponseEntity.code == 200) {
                            int i = IsVersion.compareVersion(versionCode, updateVersionBaseResponseEntity.data.getAndroid_number());
                            if (i == 1) {
                                String string = updateVersionBaseResponseEntity.data.getContent() != null ? (String)updateVersionBaseResponseEntity.data.getContent() : "";
                                String s = string.replaceAll(",", "\n");
                                if (updateVersionBaseResponseEntity.data.getUpdate_status().equals("1")) {
                                    //强制更新
                                    DialogUtils.UpDialogUrl(mainActivity,s,false,updateVersionBaseResponseEntity.data.getAndroid_url());
                                }else {
                                    //不强制更新
                                    DialogUtils.UpDialog(mainActivity,s,false,updateVersionBaseResponseEntity.data.getAndroid_url());
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }



    public void unLoadData(){

        if (mCompositeSubscription.hasSubscriptions()){
            mCompositeSubscription.unsubscribe();
        }
    }

    private void setAdapter() {

        adapter = new FunctionRecyclerAdapter(mContext);
        RecyclerView recycler = getView().getRecycler();
        recycler.setAdapter(adapter);
        adapter.setItemClickListenter((scan, position,code) -> {
            Intent intent = null;
                switch (code) {
                    case "101": //添加门店
                        if (mainActivity.locationPermission())
                            if (scan.getType().equals("1")) {
                                mainActivity.jumpToActivity(MenDianActivity.class);
                            } else {
                                intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                Uri content_url = Uri.parse(scan.getUrl());
                                intent.setData(content_url);
                                mainActivity.startActivity(intent);
                            }
                        break;
                    case "102": //激活设备
                        if (mainActivity.camePermission()) {
                            if (scan.getType().equals("1")) {
                                codeDialog.show();
                                wifi.setOnClickListener(v -> {
                                    mainActivity.sao = true;
                                    Intent intent1 = new Intent(mainActivity, CaptureActivity.class);
                                    intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                    mainActivity.startActivityForResult(intent1, REQUEST_CODE);
                                    codeDialog.dismiss();
                                });
                                mami.setOnClickListener(v -> {
                                    mainActivity.sao = false;
                                    Intent intent1 = new Intent(mainActivity, CodeActivity.class);
                                    intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                    mainActivity.startActivityForResult(intent1, REQUEST_CODE);
                                    codeDialog.dismiss();
                                });
                                dialog_photo.setOnClickListener(v -> {
                                    photo(REQUEST_CODE);
                                    codeDialog.dismiss();
                                });

                                canel.setOnClickListener(v -> codeDialog.dismiss());

                            } else {
                                intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                Uri content_url = Uri.parse(scan.getUrl());
                                intent.setData(content_url);
                                mainActivity.startActivity(intent);
                            }
                        }
                        break;
                    case "103": //配置wifi
                        if (scan.getType().equals("1")) {
                            mainActivity.jumpToActivity(WifiActivity.class);
                        } else {
                            intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri content_url = Uri.parse(scan.getUrl());
                            intent.setData(content_url);
                            mainActivity.startActivity(intent);
                        }
                        break;
                    case "104": //更新固件
                        if (mainActivity.camePermission())
                        if (scan.getType().equals("1")) {
                            codeDialog.show();
                            wifi.setOnClickListener(v -> {
                                mainActivity.sao = true;
                                Intent intent1 = new Intent(mainActivity, CaptureActivity.class);
                                intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                mainActivity.startActivityForResult(intent1, GET_FIRMWARE);
                                codeDialog.dismiss();
                            });
                            mami.setOnClickListener(v -> {
                                mainActivity.sao = false;
                                Intent intent1 = new Intent(mainActivity, CodeActivity.class);
                                intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                mainActivity.startActivityForResult(intent1, GET_FIRMWARE);
                                codeDialog.dismiss();
                            });
                            dialog_photo.setOnClickListener(v -> {
                                photo(GET_FIRMWARE);
                                codeDialog.dismiss();
                            });
                            canel.setOnClickListener(v -> codeDialog.dismiss());

                        } else {
                            intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri content_url = Uri.parse(scan.getUrl());
                            intent.setData(content_url);
                            mainActivity.startActivity(intent);
                        }
                      //  ToastUtil.showToast("正在开发中..");
                        break;
                    case "105": //常见问题
                        if (scan.getType().equals("1")) {

                        } else {
                            intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri content_url = Uri.parse(scan.getUrl());
                            intent.setData(content_url);
                            mainActivity.startActivity(intent);
                        }
                        break;
                    case "106": //统计报表
                        if (scan.getType().equals("1")) {
                            mainActivity.jumpToActivity(DateInfosActivity.class);
                        } else {
                            intent = new Intent();
                            intent.setAction("android.intent.action.VIEW");
                            Uri content_url = Uri.parse(scan.getUrl());
                            intent.setData(content_url);
                            mainActivity.startActivity(intent);
                        }
                        break;
                    case "107": //扫码充电
                        if (mainActivity.camePermission())
                            if (scan.getType().equals("1")) {
                                codeDialog.show();
                                wifi.setOnClickListener(v -> {
                                    mainActivity.sao = true;
                                    Intent intent1 = new Intent(mainActivity, CaptureActivity.class);
                                    intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                    intent1.putExtra("send_factory", SAO_CODE);
                                    mainActivity.startActivityForResult(intent1, SAO_CODE);
                                    codeDialog.dismiss();
                                });
                                mami.setOnClickListener(v -> {
                                    mainActivity.sao = false;
                                    Intent intent1 = new Intent(mainActivity, CodeActivity.class);
                                    intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                    mainActivity.startActivityForResult(intent1, SAO_CODE);
                                    codeDialog.dismiss();
                                });
                                dialog_photo.setOnClickListener(v -> {
                                    photo(SAO_CODE);
                                    codeDialog.dismiss();
                                });
                                canel.setOnClickListener(v -> codeDialog.dismiss());

                            } else {
                                intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                Uri content_url = Uri.parse(scan.getUrl());
                                intent.setData(content_url);
                                mainActivity.startActivity(intent);
                            }
                        break;
                    case "108": //设备撤回
                        if (mainActivity.camePermission())
                            if (scan.getType().equals("1")) {
                                codeDialog.show();
                                wifi.setOnClickListener(v -> {
                                    mainActivity.sao = true;
                                    Intent intent1 = new Intent(mainActivity, CaptureActivity.class);
                                    intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                    intent1.putExtra("send_factory", WITHDRAW);
                                    mainActivity.startActivityForResult(intent1, WITHDRAW);
                                    codeDialog.dismiss();
                                });
                                mami.setOnClickListener(v -> {
                                    mainActivity.sao = false;
                                    Intent intent1 = new Intent(mainActivity, CodeActivity.class);
                                    intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                    mainActivity.startActivityForResult(intent1, WITHDRAW);
                                    codeDialog.dismiss();
                                });
                                dialog_photo.setOnClickListener(v -> {
                                    photo(WITHDRAW);
                                    codeDialog.dismiss();
                                });
                                canel.setOnClickListener(v -> codeDialog.dismiss());

                            } else {
                                intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                Uri content_url = Uri.parse(scan.getUrl());
                                intent.setData(content_url);
                                mainActivity.startActivity(intent);
                            }
                        break;
                    case "109": //硬件故障
                        if (mainActivity.camePermission())
                            if (scan.getType().equals("1")) {
                                codeDialog.show();
                                wifi.setOnClickListener(v -> {
                                    mainActivity.sao = true;
                                    Intent intent1 = new Intent(mainActivity, CaptureActivity.class);
                                    intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                    mainActivity.startActivityForResult(intent1, HARDWARE_FAULT);
                                    codeDialog.dismiss();
                                });
                                mami.setOnClickListener(v -> {
                                    mainActivity.sao = false;
                                    Intent intent1 = new Intent(mainActivity, CodeActivity.class);
                                    intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                    mainActivity.startActivityForResult(intent1, HARDWARE_FAULT);
                                    codeDialog.dismiss();
                                });
                                dialog_photo.setOnClickListener(v -> {
                                    photo(HARDWARE_FAULT);
                                    codeDialog.dismiss();
                                });
//                                intent = new Intent(mainActivity, CaptureActivity.class);
//                                intent.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
//                                mainActivity.startActivityForResult(intent, HARDWARE_FAULT);
//                                intent = new Intent(mainActivity, CodeActivity.class);
//                                intent.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
//                                mainActivity.startActivityForResult(intent, HARDWARE_FAULT);
                            } else {
                                intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                Uri content_url = Uri.parse(scan.getUrl());
                                intent.setData(content_url);
                                mainActivity.startActivity(intent);
                            }
                        break;
                    case "111": //灯光控制
                        if (mainActivity.camePermission())
                            if (scan.getType().equals("1")) {
                                codeDialog.show();
                                wifi.setOnClickListener(v -> {
                                    mainActivity.sao = true;
                                    Intent intent1 = new Intent(mainActivity, CaptureActivity.class);
                                    intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                    mainActivity.startActivityForResult(intent1, GREEN_LIGHTING);
                                    codeDialog.dismiss();
                                });
                                mami.setOnClickListener(v -> {
                                    mainActivity.sao = false;
                                    Intent intent1 = new Intent(mainActivity, CodeActivity.class);
                                    intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                    mainActivity.startActivityForResult(intent1, GREEN_LIGHTING);
                                    codeDialog.dismiss();
                                });
                                dialog_photo.setOnClickListener(v -> {
                                    photo(GREEN_LIGHTING);
                                    codeDialog.dismiss();
                                });

                            } else {
                                intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                Uri content_url = Uri.parse(scan.getUrl());
                                intent.setData(content_url);
                                mainActivity.startActivity(intent);
                            }
                        break;
                    case "110":
                        //变更设备
                        if (mainActivity.camePermission())
                            if (scan.getType().equals("1")) {
                                codeDialog.show();
                                wifi.setOnClickListener(v -> {
                                    mainActivity.sao = true;
                                    Intent intent1 = new Intent(mainActivity, CaptureActivity.class);
                                    intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                    mainActivity.startActivityForResult(intent1, UPDATE_CDB);
                                    codeDialog.dismiss();
                                });
                                mami.setOnClickListener(v -> {
                                    mainActivity.sao = false;
                                    Intent intent1 = new Intent(mainActivity, CodeActivity.class);
                                    intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                    mainActivity.startActivityForResult(intent1, UPDATE_CDB);
                                    codeDialog.dismiss();
                                });
                                dialog_photo.setOnClickListener(v -> {
                                    photo(UPDATE_CDB);
                                    codeDialog.dismiss();
                                });

                            } else {
                                intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                Uri content_url = Uri.parse(scan.getUrl());
                                intent.setData(content_url);
                                mainActivity.startActivity(intent);
                            }
                        break;
                    case "112":
                        //寄回工厂
                        if (mainActivity.camePermission())
                            if (scan.getType().equals("1")) {
                                codeDialog.show();
                                wifi.setOnClickListener(v -> {
                                    mainActivity.sao = true;
                                    Intent intent1 = new Intent(mainActivity, CaptureActivity.class);
                                    intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                    intent1.putExtra("send_factory", SEND_FACTORY);
                                    mainActivity.startActivityForResult(intent1, SEND_FACTORY);
                                    codeDialog.dismiss();
                                });
                                mami.setOnClickListener(v -> {
                                    mainActivity.sao = false;
                                    Intent intent1 = new Intent(mainActivity, CodeActivity.class);
                                    intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                    mainActivity.startActivityForResult(intent1, SEND_FACTORY);
                                    codeDialog.dismiss();
                                });
                                dialog_photo.setOnClickListener(v -> {
                                    photo(SEND_FACTORY);
                                    codeDialog.dismiss();
                                });
                            } else {
                                intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                Uri content_url = Uri.parse(scan.getUrl());
                                intent.setData(content_url);
                                mainActivity.startActivity(intent);
                            }
                        break;
                    case "113":
                        //纸巾机补货
                        if (mainActivity.camePermission()) {
                            if (scan.getType().equals("1")) {
                                codeDialog.show();
                                wifi.setOnClickListener(v -> {
                                    mainActivity.sao = true;
                                    Intent intent1 = new Intent(mainActivity, CaptureActivity.class);
                                    intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                    mainActivity.startActivityForResult(intent1, PAPER_BH);
                                    codeDialog.dismiss();
                                });
                                mami.setOnClickListener(v -> {
                                    mainActivity.sao = false;
                                    Intent intent1 = new Intent(mainActivity, CodeActivity.class);
                                    intent1.putExtra("small_prompt", scan.getSmall_prompt() != null ? (String) scan.getSmall_prompt() : "");
                                    mainActivity.startActivityForResult(intent1, PAPER_BH);
                                    codeDialog.dismiss();
                                });
                                dialog_photo.setOnClickListener(v -> {
                                    photo(PAPER_BH);
                                    codeDialog.dismiss();
                                });

                                canel.setOnClickListener(v -> codeDialog.dismiss());

                            } else {
                                intent = new Intent();
                                intent.setAction("android.intent.action.VIEW");
                                Uri content_url = Uri.parse(scan.getUrl());
                                intent.setData(content_url);
                                mainActivity.startActivity(intent);
                            }
                        }
                        break;
                    default:
                        ToastUtil.showToast("请更新最新版本...");
                        break;
                }
        });
    }



    /*
        PopupWindow展示
        */
    public void selectImgs() {

        ((InputMethodManager) mainActivity.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(mainActivity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        menuWindow = new SelectPicPopupWindow(mainActivity) {

            @Override
            public View initView() {
                LayoutInflater inflater = (LayoutInflater) mainActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View menuview = inflater.inflate(R.layout.item_add_popupwindows, null);

                Button friend_item_popupwindows_new = (Button) menuview.findViewById(R.id.friend_item_popupwindows_new);   //新建
                Button friend_item_popupwindows_add = (Button) menuview.findViewById(R.id.friend_item_popupwindows_add);   //添加
                Button friend_item_popupwindows_cancel = (Button) menuview.findViewById(R.id.friend_item_popupwindows_cancel);     //刷新

                /**
                 * 取消按钮销毁事件
                 * by黄海杰@2015-1-7
                 */
                friend_item_popupwindows_cancel.setOnClickListener(v ->  dismiss());
                friend_item_popupwindows_new.setOnClickListener(v -> camera());
                friend_item_popupwindows_add.setOnClickListener(v -> gallery());
                return menuview;
            }
        };
        //设置弹窗位置
        menuWindow.showAtLocation(mainActivity.findViewById(R.id.cl), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    /*
    * 从相机获取
    */
    public void camera() {
        // 激活相机
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        // 判断存储卡是否可以用，可用进行存储
        if (hasSdcard()) {
            tempFile = new File(Environment.getExternalStorageDirectory(),
                    PHOTO_FILE_NAME);
            // 从文件中创建uri
            Uri uri = Uri.fromFile(tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CAREMA
        mainActivity.startActivityForResult(intent, PHOTO_REQUEST_CAREMA);
    }

    /*
   * 从相册获取
   */
    public void gallery() {
        // 激活系统图库，选择一张图片
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
        mainActivity.startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
    }


    /*
    * 判断sdcard是否被挂载
    */
    private boolean hasSdcard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }


    private void photo(int code) {
        mainActivity.sao = true;
        // 激活系统图库，选择一张图片
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        // 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
        mainActivity.startActivityForResult(intent, code);


//        Intent innerIntent = new Intent(); // "android.intent.action.GET_CONTENT"
//        if (Build.VERSION.SDK_INT < 19) {
//            innerIntent.setAction(Intent.ACTION_GET_CONTENT);
//        } else {
//            innerIntent.setAction(Intent.ACTION_OPEN_DOCUMENT);
//        }
//        // innerIntent.setAction(Intent.ACTION_GET_CONTENT);
//
//        innerIntent.setType("image/*");
//
//        Intent wrapperIntent = Intent.createChooser(innerIntent, "选择二维码图片");
//
//        mainActivity.startActivityForResult(wrapperIntent, code);
    }


    /**
     *  //扫一扫数据解析
     * @param qrcode
     * @param type  根据type判断是激活设备 还是扫码充电
     */
    public void parse(String qrcode,int type){
        progressDialog.show();
        String tiem = System.currentTimeMillis() + "";
        Map<String,String> map = new LinkedHashMap<>();
        map.put("rf","2");
        map.put("ts",tiem);
        map.put("v",versionCode);
        map.put("i",NetWorkCodeInfo.PARSE_v2);
        map.put("udid",udid);
        map.put("eid",id);
        map.put("qrcode",qrcode);
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry",encry1);
        System.out.println(map.toString());
        RetrofitFactory.getmInstanse().mApi.getParse(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<ParseCode>>() {
                    @Override
                    public void success(BaseResponseEntity<ParseCode> parseCodeBaseResponseEntity) {
                        if (parseCodeBaseResponseEntity.code == 200) {
                            String alias = parseCodeBaseResponseEntity.data.getAlias();
                            if (type == SAO_CODE) {
                                switch (parseCodeBaseResponseEntity.data.getDevice_type()) {
                                    //设备类型 1、WiFi 3、蓝牙 4、密码 5、纸巾机
                                    case 1:
                                        NetWork(type,alias,parseCodeBaseResponseEntity.data.getDevice_type());
                                        break;
                                    case 2:
                                        break;
                                    case 3:
                                        break;
                                    case 4:
                                        mima(alias,parseCodeBaseResponseEntity.data.getPwd_type());
                                        break;
                                    default:
                                        progressDialog.dismiss();
                                        break;
                                }
                            }else {
                                NetWork(type,alias,parseCodeBaseResponseEntity.data.getDevice_type());
                            }

                        }else {
                            progressDialog.dismiss();
                            DialogUtils.TSDialog(mContext,parseCodeBaseResponseEntity.message,true);
                        }
                    }
                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                      //  DialogUtils.TSDialog(mContext,mContext.getString(R.string.error_date),true);
                    }
                });
    }

    public void mima(String alias,String pwd_type){
        long tiem = System.currentTimeMillis()/1000;
        String url = null;
        if (pwd_type.equals("2")) {
            //https://www.wacdd.com/zhitiaoke/password/index_xdd.html?a=0111070004D9&t=1503557004
            url = "https://www.wacdd.com/zhitiaoke/password/index_xdd.html?a="+alias+"&t="+tiem;
        }else if (pwd_type.equals("3")) {
            //https://www.wacdd.com/zhitiaoke/password/index_own.html?a=0111070004D9&t=1503557004
            url = "https://www.wacdd.com/zhitiaoke/password/index_own.html?a="+alias+"&t="+tiem;
        }else{
            //https://www.wacdd.com/zhitiaoke/password/index.html?a=0111070004D9&t=1503557004
            url = "https://www.wacdd.com/zhitiaoke/password/index.html?a="+alias+"&t="+tiem;
        }
        mmsb(url);

    }

    public void mmsb(String url){
        progressDialog.dismiss();
        Intent intent = new Intent(mainActivity, WebActivity.class);
//        Intent intent = new Intent();
//        intent.setAction("android.intent.action.VIEW");
//        Uri content_url = Uri.parse(url);
//        intent.setData(content_url);
        intent.putExtra("url",url);
        mainActivity.startActivity(intent);
    }

    public void NetWork(int type, String alias,int device_type){
        Intent intent = null;
        switch (type) {
            case REQUEST_CODE:
                //激活设备
                if (mainActivity.locationPermission()) {
                    progressDialog.dismiss();
                    intent = new Intent(mainActivity, NetInActivity.class);
                    intent.putExtra("alias",alias);
                    intent.putExtra("device_type",device_type);
                    mainActivity.jumpToActivity(intent);
                }
                break;
            case PAPER_BH:
                //激活设备
                if (mainActivity.locationPermission()) {
                    progressDialog.dismiss();
                    intent = new Intent(mainActivity, PaperBHActivity.class);
                    intent.putExtra("alias",alias);
                    intent.putExtra("device_type",device_type);
                    mainActivity.jumpToActivity(intent);
                }
                break;
            case SAO_CODE:
                //扫码充电五分种
                String tiem2 = System.currentTimeMillis() + "";
                String encry2 = ObtainEncry.getStart2charging("2", tiem2, versionCode, NetWorkCodeInfo.START_CHARGING, udid,alias,id);
                RetrofitFactory.getmInstanse().mApi.getStart2charging("2", tiem2, versionCode, NetWorkCodeInfo.START_CHARGING, udid,alias,id,encry2)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new HttpObserver<BaseResponseEntity<String>>() {
                            @Override
                            public void success(BaseResponseEntity<String> stringBaseResponseEntity) {
                                if (stringBaseResponseEntity.code == 200) {
                                    handler.sendMessageDelayed(handler.obtainMessage(SAO_CODE,stringBaseResponseEntity.data), 2000);
                                }else {
                                    progressDialog.dismiss();
                                    ToastUtil.showToast(stringBaseResponseEntity.message);
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                progressDialog.dismiss();
                                super.onError(e);
                            }
                        });
                break;
            case WITHDRAW:
                progressDialog.dismiss();
                selectDialog();
                dialog.findViewById(R.id.dialog_save).setOnClickListener(v -> {
                    //设备撤回
                    String tiem3 = System.currentTimeMillis() + "";
                    String encry3 = ObtainEncry.getStart2charging("2", tiem3, versionCode, NetWorkCodeInfo.WITHDRAW, udid,alias,id);
                    RetrofitFactory.getmInstanse().mApi.getWithdraw("2", tiem3, versionCode, NetWorkCodeInfo.WITHDRAW, udid,alias,id,encry3)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new HttpObserver<BaseResponseEntity<String>>() {
                                @Override
                                public void success(BaseResponseEntity<String> stringBaseResponseEntity) {
                                    if (stringBaseResponseEntity.code == 200) {
                                        ToastUtil.showToast(mainActivity.getString(R.string.success_revocation));
                                    }else {
                                        ToastUtil.showToast(stringBaseResponseEntity.message);
                                    }
                                    dialog.dismiss();
                                }

                                @Override
                                public void onError(Throwable e) {
                                    super.onError(e);
                                    dialog.dismiss();
                                    ToastUtil.showToast(mainActivity.getString(R.string.error_revocation));
                                }
                            });
                });

                break;
            case HARDWARE_FAULT:
                //硬件故障
                progressDialog.dismiss();
                intent = new Intent(mainActivity, HardwareActivity.class);
                intent.putExtra("alias",alias);
                mainActivity.jumpToActivity(intent);
                break;
            case GREEN_LIGHTING:
                //灯光控制
                progressDialog.dismiss();
                intent = new Intent(mainActivity, LamplightActivity.class);
                intent.putExtra("alias",alias);
                mainActivity.jumpToActivity(intent);
                break;
            case UPDATE_CDB:
                //变更设备
                progressDialog.dismiss();
                intent = new Intent(mainActivity, UpdateCdbActivity.class);
                intent.putExtra("alias",alias);
                mainActivity.jumpToActivity(intent);
                break;
            case GET_FIRMWARE:
                //更新固件
                progressDialog.dismiss();
                intent = new Intent(mainActivity, FirmwareActivity.class);
                intent.putExtra("alias",alias);
                mainActivity.jumpToActivity(intent);
                break;
            case SEND_FACTORY:
                //寄回工厂
                String tiem4 = System.currentTimeMillis() + "";
                String encry4 = ObtainEncry.getStart2charging("2", tiem4, versionCode, NetWorkCodeInfo.GET_HARDWARE_REPORT, udid,alias,id);
                RetrofitFactory.getmInstanse().mApi.get_hardware_report("2", tiem4, versionCode, NetWorkCodeInfo.GET_HARDWARE_REPORT, udid,alias,id,encry4)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new HttpObserver<BaseResponseEntity<Hardware_report>>() {
                            @Override
                            public void success(BaseResponseEntity<Hardware_report> stringBaseResponseEntity) {
                                if (stringBaseResponseEntity.code == 200) {
                                    progressDialog.dismiss();
                                    if (stringBaseResponseEntity.data != null){
                                        Intent intent  = new Intent(mainActivity, GetHardwareActivity.class);
                                        intent.putExtra("alias",alias);
                                        intent.putExtra("name",stringBaseResponseEntity.data.getEmployee().getName());
                                        intent.putExtra("mobile",stringBaseResponseEntity.data.getEmployee().getMobile());
                                        intent.putExtra("time",stringBaseResponseEntity.data.getCreated());
                                        String remark = "";
                                        if (stringBaseResponseEntity.data.getContent() != null) {
                                            remark = stringBaseResponseEntity.data.getContent();
                                        }
                                        intent.putExtra("remark",remark);
                                        mainActivity.startActivity(intent);
                                    }else {
                                        Dialog(alias);
                                    }
                                }else {
                                    progressDialog.dismiss();
                                    ToastUtil.showToast(stringBaseResponseEntity.message);
                                }
                            }
                            @Override
                            public void onError(Throwable e) {
                                super.onError(e);
                                progressDialog.dismiss();
                                ToastUtil.showToast(mainActivity.getString(R.string.error_factory));
                            }
                        });
                break;
        }
    }


    public void save(String alias){
        //寄回工厂
        String tiem4 = System.currentTimeMillis() + "";
        String encry4 = ObtainEncry.getStart2charging("2", tiem4, versionCode, NetWorkCodeInfo.SEND_FACTORY, udid,alias,id);
        RetrofitFactory.getmInstanse().mApi.getSend_factory("2", tiem4, versionCode, NetWorkCodeInfo.SEND_FACTORY, udid,alias,id,encry4)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<String>>() {
                    @Override
                    public void success(BaseResponseEntity<String> stringBaseResponseEntity) {
                        if (stringBaseResponseEntity.code == 200) {
                            ToastUtil.showToast(mContext.getString(R.string.success_factory));
                        }else {
                            ToastUtil.showToast(stringBaseResponseEntity.message);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        ToastUtil.showToast(mContext.getString(R.string.error_factory));
                    }
                });

    }



    String ii;
    String mm;
    int nn = 0;
    //查询指令链路情况
    public void getMessage(String i,String message){
        ii = i;
        mm = message;
        String tiemMessage = System.currentTimeMillis() + "";
        String encryMessage = ObtainEncry.getMessage("2", tiemMessage, versionCode, i, udid, message);

        RetrofitFactory.getmInstanse().mApi.getMessage("2", tiemMessage, versionCode, i, udid, message, encryMessage)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<String>>() {
                    @Override
                    public void success(BaseResponseEntity<String> stringBaseResponseEntity) {

                        if (stringBaseResponseEntity.code == 200) {
                            nn = 0;
                            progressDialog.dismiss();
                            ToastUtil.showToast(mainActivity.getString(R.string.success));
                        }else {
                            if (nn < 5) {
                                Observable.timer(2, TimeUnit.SECONDS).subscribe(aLong -> {
                                    getMessage(ii,mm);
                                    nn++;
                                });
                            }else {
                                nn = 0;
                                progressDialog.dismiss();
                                ToastUtil.showToast(stringBaseResponseEntity.message);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        nn = 0;
                        progressDialog.dismiss();
                        ToastUtil.showToast(mainActivity.getString(R.string.error_hint));
                    }
                });
    }


    public void dialog(){
        progressDialog = new Dialog(mainActivity,R.style.progress_dialog);
        progressDialog.setContentView(R.layout.dialog);
        progressDialog.setCancelable(true);
        progressDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        TextView msg = (TextView) progressDialog.findViewById(R.id.id_tv_loadingmsg);
        msg.setText("正在加载中.");
        progressDialog.show();
    }

    private void Dialog(String alias) {
        selfDialog = new SimpleDialog(mContext);
        selfDialog.setTitle("提示");
        selfDialog.setMessage("该设备并未填写损坏信息，是否直接寄回工厂");
        selfDialog.setYesOnclickListener("确定", () -> {
            save(alias);
            selfDialog.dismiss();
        });
        selfDialog.setNoOnclickListener("取消", () -> {
            selfDialog.dismiss();
        });
        selfDialog.show();
    }

    public void selectDialog(){
        dialog = DialogUtils.ClickDialog(mContext, "是否撤回该设备", true);
        dialog.findViewById(R.id.dialog_cancel).setVisibility(View.VISIBLE);
        dialog.findViewById(R.id.dialog_cancel).setOnClickListener(v -> {
            dialog.dismiss();
        });
    }

    /**
     * 二维码扫描选择dialog
     */
    public void CodeDialog(){
        codeDialog = DialogUtils.CodeDialog(mContext);
        canel = (TextView) codeDialog.findViewById(R.id.dialog_cancel);
        wifi = (TextView) codeDialog.findViewById(R.id.dialog_wifi);
        mami = (TextView) codeDialog.findViewById(R.id.dialog_mima);
        dialog_photo = (TextView) codeDialog.findViewById(R.id.dialog_photo);
    }


    //获取所有用户数据
    int a = 0;
    int b = 0;
    private void netWork() {
        String tiem = System.currentTimeMillis() + "";
        Map<String,String> map = new LinkedHashMap<>();
        map.put("rf","2");
        map.put("ts",tiem);
        map.put("v", versionCode);
        map.put("i", NetWorkCodeInfo.ALL);
        map.put("udid",udid);
        map.put("eid",id);
        String encry1 = ObtainEncry.getEncry(map);
        map.put("encry",encry1);
        RetrofitFactory.getmInstanse().mApi.getAllUser(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new HttpObserver<BaseResponseEntity<List<AllUser>>>() {
                    @Override
                    public void success(BaseResponseEntity<List<AllUser>> listBaseResponseEntity) {
                        if (listBaseResponseEntity.code == 200) {
                            List<AllUser> data = listBaseResponseEntity.data;
                            for (int i = 0; i < data.size(); i++) {
                                if (data.get(i).getId().equals(id) && ("总后台".equals(data.get(i).getCity_name()) || data.get(i).getAdmin().equals("1"))) {
                                    a = 1;
                                    main_cut_user.setVisibility(View.VISIBLE);
                                }else {
                                    if (a == 1) {

                                    }else{
                                        getView().getMain_gz().setVisibility(View.GONE);
                                        getView().getMain_ch().setVisibility(View.GONE);
                                        main_cut_user.setVisibility(View.GONE);
                                    }

                                }
                                if (data.get(i).getId().equals(id) && data.get(i).getAdmin().equals("1")) {
                                    b = 1;
                                    getView().getMain_gz().setVisibility(View.VISIBLE);
                                    getView().getMain_ch().setVisibility(View.GONE);
                                }else {
                                    if (b == 1) {

                                    }else{
                                        getView().getMain_gz().setVisibility(View.GONE);
                                        getView().getMain_ch().setVisibility(View.VISIBLE);
                                    }

                                }
                            }
                            main_cut_user.setOnClickListener(v -> {
                                Intent intent = new Intent(mainActivity, GroupingActivity.class);
                                intent.putExtra("date", (Serializable) data);
                                intent.putExtra("admin", b);
                                mainActivity.startActivityForResult(intent,CUT_USER);
                            });
                        }else{
//                            DialogUtils.TSDialog(mContext,listBaseResponseEntity.message,true);
                        }
                    }
                    @Override
                    public void onError(Throwable e) {
                     //   DialogUtils.TSDialog(mContext,mContext.getString(R.string.error_date),true);
                    }
                });
    }
}
